package cn.sskxyz.security.resource.authorization;

import cn.sskxyz.security.core.model.User;
import cn.sskxyz.security.resource.property.ResourceServerSystemProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证服务提供权限检查接口，这里通过http请求检查用户是否有权限操作
 */
public class RbacPermissionValidator implements PermissionValidator {

    private static final Logger logger = LoggerFactory.getLogger(RbacPermissionValidator.class);

    private ResourceServerSystemProperty systemProperty;

    private RestTemplate restTemplate = new RestTemplate();

    public RbacPermissionValidator(ResourceServerSystemProperty systemProperty) {
        this.systemProperty = systemProperty;
    }

    @Override
    public boolean hasPermission(String url, User user) {
        Map<String, String> request = new HashMap<>();
        request.put("module", systemProperty.getSystemId());
        request.put("userId", String.valueOf(user.getId()));
        request.put("uri", url);

        ResponseEntity<String> response = restTemplate.postForEntity(systemProperty.getCheckAddr() + "?module={module}&userId={userId}&uri={uri}", null, String.class, request);
        if (response.getStatusCode() == HttpStatus.OK) {
            return true;
        }
        logger.info("权限不足,当前请求的uri为：{},请求的用户为:{}", url, user.getUsername());
        return false;
    }
}
